import React, { useContext, useEffect } from "react";
import { useSetRecoilState } from "recoil";
import { getSiteInfo } from "./api";
import { ISiteInfo } from "./interface";
import { siteInfo } from "./recoil/atoms/siteInfo";
import { isInAdminRoute, verify } from "./util";

interface AuthContextType {
  isLogin: boolean;
}

const AuthContext = React.createContext<AuthContextType>({
  isLogin: false,
});

export function AuthProvider({ children }: { children: React.ReactNode }) {

  const setCompanyInfo = useSetRecoilState<ISiteInfo>(siteInfo);

  const isLogin = !!localStorage.getItem('userInfo');
  const value = { isLogin };

  useEffect(() => {
    if (!isLogin && isInAdminRoute()) {
      verify();
    } else {
      getSiteInfo().then((companyData: ISiteInfo) => {
        setCompanyInfo(companyData);
        if (companyData.companyName) {
          document.title = companyData.companyName
        }
      })
    }
  }, []);

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth() {
  return useContext(AuthContext);
}
